<?php

namespace AntStudio\AntToolsSdk\wetchat\wetchat;
/**
 *https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
 *微信网页开发 /网页授权
 */
class UserAuth
{
    /**
     * APPid
     * @var mixed
     */
    private $appid;
    /**
     * 公众号秘钥
     * @var mixed
     */
    private $secret;

    public function __construct($param)
    {
        $this->appid  = $param['appid'];
        $this->secret = $param['secret'];
    }

    // function __construct($params)
    // {
    // 	# code...
    // }
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https://chong.qq.com/php/index.php?d=&c=wxAdapter&m=mobileDeal&showwxpaytitle=1&vb2ctag=4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http://nba.bluewebgame.com/oauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    /**
     * [getLoginUrl 获取登陆地址]
     *
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function getLoginUrl($params)
    {
        $appid         = $this->appid;
        $response_type = 'code';
        $scope         = $params['scope']; //'snsapi_userinfo'; //snsapi_base  不弹出授权页面，直接跳转，只能获取用户openid ,snsapi_userinfo（弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）
        $state         = time();
        $lastUrl       = '#wechat_redirect';
        $redirect_uri  = urlEncode($params['redirect_uri']);
        if ($scope == 'snsapi_base') {
            $urlLogin = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=$response_type&scope=$scope&state=$state$lastUrl";
        } else if ($scope == 'snsapi_userinfo') {
            $urlLogin = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=$response_type&scope=$scope&state=$state$lastUrl";
        }

        return $urlLogin;
    }

    /**
     * 获取授权信息
     * @param $code
     * @param $scope
     * @return void
     */
    public function getAuthInfo($code, $scope = 'snsapi_base')
    {
//        $code = $_GPC['code'];
        //地址跳转精英
//        $scope = $_GPC['scope'];
//        $state = $_GPC['state'];
        //进行地址转向的地址
//        $navurl = $_GPC['navurl'];
        $rst = self::getAccessTokenCode($code);
        if ($scope == 'snsapi_base') {
            return $rst;
        } else if ($scope == 'snsapi_userinfo') {
            $rstUser = self::getUserInfo($rst['access_token'], $rst['refresh_token'], $rst['openid']);
            if ($rstUser['errcode'] == 0) {
                //sex 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
//                $headimgurl = $rstUser['headimgurl'];
//                echo "<br>";echo "<br>";echo "<br>";
//                echo 'openid#' . $rstUser['openid'];
//                echo "<br>";
//                echo 'unionid#' . $rstUser['unionid'];
//                echo "<br>";
//                echo 'nickname#' . $rstUser['nickname'];
//                echo "<br>";
//                echo 'sex#' . $rstUser['sex'];
//                echo "<br>";
//                echo "<image src='$headimgurl'></image>";
//
//                if ($rst['errcode'] == 0) {
//                    //header('Location:' . $navurl);
//                }
                return $rstUser;
            } else {
//                echo "string";
//                dump($rstUser);
                return $rstUser;
            }
        }
    }

    public function getBrowserAddress()
    {
        //echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        return 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];

    }

    /**
     * [getAccessTokenCode 通过code换取网页授权access_token]
     * @param  [type] $code [description]
     * @return [type]       [description]
     */
    function getAccessTokenCode($code)
    {
        $appid    = $this->appid;
        $secret   = $this->secret;
        $url      = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $response = self::httpGet($url);
        if (!isset($response['errcode'])) {
            $response['errcode'] = 0;
        }

        return $response;
    }

    /**
     * [refreshAccessTokenCode 第三步：刷新access_token（如果需要）]
     * @param  [type] $refresh_token [description]
     * @return [type]                [description]
     */
    function refreshAccessTokenCode($refresh_token)
    {
        $appid    = $this->appid;
        $url      = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
        $response = self::httpGet($url);

        return $response;
    }

    /**
     * [getUserInfo 第四步：拉取用户信息 逻辑]
     * @param  [type] $access_token  [description]
     * @param  [type] $refresh_token [description]
     * @param  [type] $openid        [description]
     * @param string $lang [description]
     * @return [type]                [description]
     */
    function getUserInfo($access_token, $refresh_token, $openid, $lang = 'zh_CN')
    {
        $rst = self::checCodeAccessToken($access_token, $openid);
        if ($rst['errcode'] == 0) {
            return self::getUserInfoBase($access_token, $openid, $lang);
        } else {
            $refrshRst = self::refreshAccessTokenCode($refresh_token);

            return self::getUserInfoBase($refrshRst['access_token'], $openid, $lang);
        }
    }

    /**
     * [getUserInfoBase 第四步：拉取用户信息(需scope为 snsapi_userinfo)]
     * @param  [type] $access_token [description]
     * @param  [type] $openid       [description]
     * @param string $lang [description]
     * @return [type]               [description]
     */
    function getUserInfoBase($access_token, $openid, $lang = 'zh_CN')
    {
        $url      = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=$lang";
        $response = self::httpGet($url);
        if (!isset($response['errcode'])) {
            $response['errcode'] = 0;
        }

        return $response;
    }

    /**
     * [checCodeAccessToken 检验授权凭证（access_token）是否有效]
     * https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
     * @param  [type] $access_token [description]
     * @param  [type] $openid       [description]
     * @return [type]               [description]
     */
    function checCodeAccessToken($access_token, $openid)
    {
        $url      = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
        $response = self::httpGet($url);

        return $response;
    }

    function dump($vars, $label = '', $return = false)
    {
        if (ini_get('html_errors')) {
            $content = "<pre>\n";
            if ($label != '') {
                $content .= "<strong>{$label} :</strong>\n";
            }
            $content .= htmlspecialchars(print_r($vars, true));
            $content .= "\n</pre>\n";
        } else {
            $content = $label . " :\n" . print_r($vars, true);
        }
        if ($return) {
            return $content;
        }
        echo $content;

        return null;
    }

    function httpGet($url, $json_transfer_back = 1)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        if ($json_transfer_back == 1) {
            $data = json_decode($data, true);
        }

        return $data;
    }
}